package com.example.travel.controller;

import com.alibaba.fastjson.JSON;
import com.example.travel.pojo.message.FMessage;
import com.example.travel.pojo.message.UserMessageType;
import com.example.travel.pojo.orm.GroupUser;
import com.example.travel.pojo.orm.UserMessage;
import com.example.travel.service.GroupUserService;
import com.example.travel.service.UserMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@ServerEndpoint(value = "/webSocket/{userId}")
@Component
public class TravelWebSocket {
    @Autowired
    private GroupUserService groupUserService;

    private static UserMessageService userMessageService;

    private static int onlineCount = 0;
    private static ConcurrentHashMap<Integer, TravelWebSocket> webSocketMap = new ConcurrentHashMap<>();

    private Session session;

    private Integer userId = null;

    @Autowired
    public void setUserMessageService(UserMessageService userMessageService){
        TravelWebSocket.userMessageService = userMessageService;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")String Id){
        this.session = session;
        this.userId = Integer.parseInt(Id);
        if (webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
        }else {
            webSocketMap.put(userId,this);
            onlineCount++;
        }
        System.out.println("用户连接");
        log.info("用户连接"+userId+",当前在线人数："+onlineCount);
    }

    @OnMessage
    public void onMessage( String message,Session session){
        log.info("用户消息："+userId+",报文："+message);
        if (message!=null && !message.equals("")){
             List<Session> sessions = parseMessage(message);
             if (sessions!=null && sessions.size()!=0){
                 sendMessage(message,sessions);
             }
        }
    }

    @OnClose
    public void onClose(){
        webSocketMap.remove(userId);
        subOnlineCount();
        log.info("用户退出："+userId+",当前在线人数为："+getOnlineCount());
    }

    public Session getSession() {
        return session;
    }

    public List<Session> parseMessage(String str){
        UserMessage message = JSON.parseObject(str, UserMessage.class);
        List<Session> sessions = new ArrayList<>();
        if (webSocketMap.containsKey(message.getUserTo())){
            sessions.add(webSocketMap.get(message.getUserTo()).getSession());
        }
        System.out.println(userMessageService==null);
        System.out.println("message="+message);
        userMessageService.addMessage(message);
        return sessions;
    }

    public void sendMessage(String message, List<Session> list){
        try{
            for (Session session : list) {
                if (session!=this.session){
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获得此时的
     * 在线人数
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人
     * 数加1
     */
    public static synchronized void addOnlineCount() {
        TravelWebSocket.onlineCount++;
    }

    /**
     * 在线人
     * 数减1
     */
    public static synchronized void subOnlineCount() {
        TravelWebSocket.onlineCount--;
    }

}
